<?php
	
	namespace Aspic;

	class Request {
		
		/**
		 * @var string Url of the application used instead of calling Request::getScriptBaseUrl();
		 * Sometimes, the application is in a subfolder but the user should not know this.
		 */
		protected static $_requestUriBase = null;
		
		protected static $_scriptBaseUrl = null;
		
		/**
		* Return the url to the folder of the current script (works with url rewriting) => Web site url
		* ex: http://www.website.com/folder1/index.php 
		* => http://www.website.com/folder1
		* ex: http://www.website.com/folder/url/rewriting/part/index.php 
		* => http://www.website.com/folder (because the current script is index.php in "folder" - redirected with .htaccess)
		*/
		public static function getScriptBaseUrl() {
			if (!is_null(static::$_scriptBaseUrl)) {
				return static::$_scriptBaseUrl;
			}
			
			if(isset($_SERVER['HTTPS'])) {
				$hostUrl = 'https';
			}
			else {
				$hostUrl = 'http';
			}
			
			$hostUrl .= '://'.$_SERVER['HTTP_HOST'];
			$scriptDir = dirname($_SERVER['SCRIPT_NAME']);
			
			$scriptDir = rtrim($scriptDir, '/');
			
			$baseUrl = $hostUrl.$scriptDir;
			
			return $baseUrl;
		}
		
		/**
		* Return the REQUEST_URI without current dir path and without start '/'
		* ex:
		* REQUEST_URI = /folder1/folder2/module/controller/action
		* dirname(SCRIPT_NAME) = /folder1/folder2
		* => return module/controller/action
		*/
		public static function getRequestUriBase() {
			if (!is_null(static::$_requestUriBase)) {
				return static::$_requestUriBase;
			}
			
			$requestUri = $_SERVER['REQUEST_URI'];

			if(strpos($requestUri, '?')) {
				$requestUri = substr($requestUri, 0, strpos($requestUri, '?')); // Remove query string
			}
			
			$scriptNameDir = dirname($_SERVER['SCRIPT_NAME']);
			$scriptNameDir = str_replace('\\', '/', $scriptNameDir);
			
			$pos = strpos($requestUri, $scriptNameDir);
			
			if ($pos === false) {
				throw new Exception('Can\'t find "'.$scriptNameDir.'" in "'.$requestUri.'".');
			}
			
			$lastSlashCount = 1; // $_SERVER['SCRIPT_NAME'] have always a "/" at the beginning even when there is no subfolder following
			
			if($scriptNameDir == '/') {
				$lastSlashCount = 0;
			}
			
			$baseUrl = substr($requestUri, $pos + strlen($scriptNameDir) + $lastSlashCount);
			
			return $baseUrl;
		}
		
		public static function setScriptBaseUrl($str) {
			static::$_scriptBaseUrl = $str;
		}
		
		public static function setRequestUriBase($str) {
			static::$_requestUriBase = $str;
		}
		
		public static function isAjax() {
			return (array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
		}
		
				
		public static function registerGetParams(array $params) {
			foreach($params as $k => $v) {
				$_GET[$k] = $v;
				$_REQUEST[$k] = $v;
			}
		}
		
	}
	
?>